package cn.learn.server;

import java.util.concurrent.LinkedBlockingQueue;

public class RequestThrottler extends Thread {
    private final LinkedBlockingQueue<Request> submittedRequests = new LinkedBlockingQueue<Request>();
    private final ZooKeeperServer zks;

    public RequestThrottler(ZooKeeperServer zks) {
        this.zks = zks;
    }

    public void submitRequest(Request request) {
        submittedRequests.add(request);
    }

    @Override
    public void run() {
        try {
            while (true) {
                System.out.println("启动节流器线程");
                Request request = submittedRequests.take();
                if (request != null) {
                    zks.submitRequestNow(request);
                }
            }
        }catch (Exception e) {

        }
        int dropped = drainQueue();
    }

    private int drainQueue() {
        int dropped = 0;
        Request request;
        while ((request = submittedRequests.poll()) != null) {
        }
        return dropped;
    }
}
